import express from "express";
import expressWs from "express-ws";

const router = express.Router();
const app = express();
expressWs(app); //混入功能，使router支持ws方法
const wsClients = [];

/**
 * 解决跨域
 */
const cors = (req, res, next) => {
	//设置允许跨域的域名，*代表允许任意域名跨域
	res.header("Access-Control-Allow-Origin", "*");
	//允许的header类型
	res.header("Access-Control-Allow-Headers", "*");
	res.header("Access-Control-Allow-Credentials", true);
	//跨域允许的请求方式
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("Content-Type", "application/json;charset=utf-8");

	if (req.method.toLowerCase() === "options")
		res.sendStatus(200); //让options尝试请求快速结束
	else next();
};

/**
 * 接收client的command请求
 * @param cmd
 */
function get(cmd) {
	console.log(cmd);
}

/**
 * 发送command到client端
 * @param msg
 * @param cb
 */
function send(msg: string, cb) {
	cb.send(msg);
}

/**
 * 设置ws的回调方法
 */
function callback(ws, req, next) {
	// 有客户端连接时, 打印一条日志
	console.log("client connect to server successful!", req, next);
	// 保存客户端标识
	wsClients.push(ws);
	ws.on("connect", () => {
		ws.send("hello, I am wss");
	});
	// 创建message监听
	ws.on("message", (msg) => {
		// 直接将消息打印出来
		console.log("receive client msg :", msg);
		//处理接收的消息
		get(msg);
		send("演示自动回复一个消息", ws);
	});
	//监听客户端断连
	ws.on("close", function (msg) {
		console.log("client is closed", msg);
		for (var index = 0; index < wsClients.length; index++) {
			if (wsClients[index] === this) {
				wsClients.splice(index, 1);
			}
		}
	});
}

//合并app
// import appExp from "./server";
// const newApp = {...app,...appExp}
/**
 * 构造路由
 */
router.ws("/*", callback);

app.use("/ws", cors, router);
export default app;
